<?php
require('../includes/class.main.php');
$manager = new MeetingManager();
require('../includes/class.geocode.php');

include('../template/admin-header.php');

	$lookup = new MeetingLookup();
	$db = new DB();
	
	$outcome = "";

	if (!isset($_POST['submit']))
	{
		$focus_zip = "";
		$focus_time_hm = "";
		
		if (isset($_GET['addmode'])) // add mode, show empty form
		{
			$_SESSION['uiState'] = "ADD";
			
			$location		= "";
			$groupName		= "";
			$address1		= "";
			$address2		= "";
			$locationNotes	= "";
			$city			= "";
			$zip			= "";
			$quadrant		= "";
			$day			= "";
			$time			= "";
			$time_hm		= "";
			$time_meridian	= "";
			$codes			= "";
			$codesA			= array();
			$groupNotes		= "";
		}
		else // change or delete mode, populate form
		{
			$rownr = $_GET['row'];
			$_SESSION['drow'] = $rownr;
			$_SESSION['uiState'] = "CHANGE_DEL";

			$query_result = $db->setQuery("select * from meetings where row = $rownr");
			$row = $query_result->fetch_assoc();
			
			$location		= $row['location'];
			$groupName		= $row['name'];
			$address1		= $row['address1'];
			$address2		= $row['address2'];
			$locationNotes	= $row['locationNotes'];
			$city			= $row['city'];
			$zip			= $row['zip'];
			$quadrant		= $row['quadrant'];
			$day			= $row['day'];
			$time			= $row['time'];
			$time_hm		= substr($time, 0, strpos($time, ' '));
			$time_meridian	= substr($time, strpos($time, ' ') + 1, strlen($time) - strpos($time, ' ') - 1);
			$codes			= $row['codes'];
			$codesA 		= explode(',', $codes);
			$groupNotes		= $row['groupNotes'];
		}
	}
	else // Form was posted for meeting deletion, change, or addition (or operation was cancelled)
	{
		$focus_zip = $_SESSION['focus_zip'];
		$focus_time_hm = $_SESSION['focus_time_hm'];
		
		$location		= $_POST['location'];
		$groupName		= $_POST['groupName'];
		$address1		= $_POST['address1'];
		$address2		= $_POST['address2'];
		$locationNotes	= $_POST['locationNotes'];
		$city			= $_POST['city'];
		$zip			= $_POST['zip'];
		$quadrant		= $_POST['quadrant'];
		$day			= $_POST['day'];
		$time_hm		= $_POST['time_hm'];
		$time_meridian	= $_POST['time_meridian'];
		$time			= $time_hm . " " . $time_meridian;
		if (!isset($_POST['codesPostUserEdits']))
			$codesA		= array();
		else
			$codesA		= $_POST['codesPostUserEdits'];
		$codes			= implode(',', $codesA);
		$groupNotes		= $_POST['groupNotes'];
		
		$geocoder = new GeocodeManager();
		if ($_POST['submit'] == "Delete Meeting")
		{
			// delete row and set message
			$rownr = $_SESSION['drow'];
			$query_result = $db->setQuery("delete from meetings where row = $rownr");

			$dberr = $db->getError();
			if ($dberr == "") {
				
				$status = $geocoder->meetingDeleted($address1,$city,$zip);
				if ($status) {
					$outcome = "<p style='color: red;'>Meeting deleted. Geocoding error [status=$status]</p>";				
				} else {
					$outcome = "<a href=\"index.php\" style='color: blue;'>Meeting deleted, click 'Continue' to proceed.</a>";
				}
			} else {
				$outcome = "<p style='color: red;'>Operation failed. [advice=$dberr]</p>";
			}
				
			$_SESSION['uiState'] = "CONTINUE_DELETE";
		}
		else  // adding or changing
		{
			// Standardize and validate form information
			$focus_zip = "";
			$focus_time_hm = "";
			$errortext = standardizeMeeting();
			$_SESSION['focus_zip'] = $focus_zip;
			$_SESSION['focus_time_hm'] = $focus_time_hm;

			if ($errortext == "")
			{
				/*
				if ($_SESSION['uiState'] == "ADD") IE session weirdness
				*/
								
				if ($_POST['submit'] == "Add Meeting")
				{
					// add row and set message
					$query_result = $db->setQuery("insert into meetings "
						. "(location,name,address1,address2,locationNotes,city,zip,quadrant,day,time,codes,groupNotes,updated) "
						. "values (\"$location\",\"$groupName\",\"$address1\",\"$address2\",\"$locationNotes\",\"$city\","
						. "\"$zip\",\"$quadrant\",\"$day\",\"$time\",\"$codes\",\"$groupNotes\",NOW())");
					$dberr = $db->getError();
					if ($dberr != "") {
						$outcome ="<p style='color: red;'>Addition failed. [advice=$dberr]</p>";
					} else {
						$status = $geocoder->meetingAdded($address1,$city,$zip);
						if ($status) {
							$outcome = "<p style='color: red;'>Meeting added. Geocoding error [status=$status]</p>";				
						} else {
							$outcome = "<a href=\"index.php\" style='color: blue;'>Meeting added, click 'Continue' to proceed.</a>";
						}
					}
					$_SESSION['uiState'] = "CONTINUE_ADD";
				}
				/*
				else  // uiState must be CHANGE_DEL
				*/
				else if ($_POST['submit'] == "Save Changes")
				{
					// update row and set message
					$rownr = $_SESSION['drow'];
					$query_result = $db->setQuery("update meetings SET "
						. "location=\"$location\","
						. "name=\"$groupName\","
						. "address1=\"$address1\","
						. "address2=\"$address2\","
						. "locationNotes=\"$locationNotes\","
						. "city=\"$city\","
						. "zip=\"$zip\","
						. "quadrant=\"$quadrant\","
						. "day=\"$day\","
						. "time=\"$time\","
						. "codes=\"$codes\","
						. "groupNotes=\"$groupNotes\", updated=NOW()"
						. "where row = $rownr");
					$dberr = $db->getError();
					if ($dberr != "") {
						$outcome = "<p style='color: red;'>Update failed. [advice=$dberr]</p>";
					} else {
						$status = $geocoder->meetingUpdated($address1,$city,$zip);
						if ($status) {
							$outcome = "<p style='color: red;'>Meeting updated. Geocoding error [status=$status]</p>";				
						} else {
							$outcome = "<a href=\"index.php\" style='color: blue;'>Meeting changed, click 'Continue' to proceed.</a>";
						}
					}
					$_SESSION['uiState'] = "CONTINUE_CHANGE_DEL";
				}
			}
			else
			{
				$outcome = "<p><ul style='color: red;'>" . $errortext . "</ul></p>";
			}
		}
	}
	$ts = 80;
	
	$abled = "";
	if (isset($_SESSION['uiState']))
	{
		if ($_SESSION['uiState'] == "CONTINUE_ADD"
			|| $_SESSION['uiState'] == "CONTINUE_DELETE"
			|| $_SESSION['uiState'] == "CONTINUE_CHANGE_DEL") $abled = "disabled";
	}
?>

<div class="left">
<?php 
include('../admin/menu.php');
?>
</div>

<div class="right">
	<h1><b><span class="blue">
	 
	<?php if ($_SESSION['uiState'] == "ADD") { ?>
		Add Meeting
	<?php } else if($_SESSION['uiState'] == "CONTINUE_ADD") { ?>
		(Meeting Added)
	<?php } else if ($_SESSION['uiState'] == "CONTINUE_DELETE") { ?>
		(Meeting Deleted)
	<?php } else if ($_SESSION['uiState'] == "CONTINUE_CHANGE_DEL") { ?>
		(Meeting Changed)
	<?php } else { ?>
		Change or Delete Meeting
	<?php } ?>
	
	</span></b>
	
	</h1>
	
	<?php 
	if (isset($outcome) && $outcome != "") {
		echo $outcome; 
	}
	?>
	
	<br />
	
	
	<form action="editmeeting.php" method="post">
		<div class="adminForm">
			<span class="label col1"><b>Group</b></span>
			<input  class="required" type="text" name="groupName" style="width:28em" required <?php echo $abled; ?> value="<?php echo $groupName; ?>">
			<br>
			<span class="label col1"><b>Day</b></span>
			<select name="day" class="required" <?php echo $abled; ?> >
				<?php if ($day == "") { $day = "SUNDAY";} ?>
				<option <?php if ($day == "SUNDAY") echo "value='$day' selected"; ?>>SUNDAY</option>
				<option <?php if ($day == "MONDAY") echo "value='$day' selected"; ?>>MONDAY</option>
				<option <?php if ($day == "TUESDAY") echo "value='$day' selected"; ?>>TUESDAY</option>
				<option <?php if ($day == "WEDNESDAY") echo "value='$day' selected"; ?>>WEDNESDAY</option>
				<option <?php if ($day == "THURSDAY") echo "value='$day' selected"; ?>>THURSDAY</option>
				<option <?php if ($day == "FRIDAY") echo "value='$day' selected"; ?>>FRIDAY</option>
				<option <?php if ($day == "SATURDAY") echo "value='$day' selected"; ?>>SATURDAY</option>
			</select>
			<span class="label"><b>Time</b></span>
			<input type="text" class="required" name="time_hm" required maxlength="255" style="width:3em" <?php echo $abled . " " . $focus_time_hm; ?> value="<?php echo $time_hm; ?>">
			<select name="time_meridian" class="required" <?php echo $abled; ?> >
				<?php if ($time_meridian == "") $time_meridian="PM" ?>
				<option <?php if ($time_meridian == "AM") echo "value='$time_meridian' selected"; ?>>AM</option>
				<option <?php if ($time_meridian == "PM") echo "value='$time_meridian' selected"; ?>>PM</option>
			</select>
			<br>
			<span class="label col1"><b>Address1</b></span>
			<input type="text" name="address1" class="required"  style="width:28em" required <?php echo $abled; ?> value="<?php echo $address1; ?>" />
			<br>
			<span class="label col1">Address2</span>
			<input type="text" name="address2"  style="width:28em" <?php echo $abled; ?> value="<?php echo $address2; ?>" />
			<br>
			<span class="col1 label" ><b>City</b></span>
			<input type="text" name="city" class="required" required  style="width:11.5em" <?php echo $abled; ?> value="<?php echo $city; ?>" />
			<span class="label" ><b>Zip</b></span>
			<input type="text" name="zip" class="required" required  style="width:4em" <?php echo $abled . " " . $focus_zip; ?> value="<?php echo $zip; ?>" />
			<span class="label">Quadrant</span>
	  		<select name="quadrant" <?php echo $abled; ?>>
				<option <?php if ($quadrant == "") echo "value=\"\" selected"; ?>> </option>
				<option <?php if($quadrant == "NE") echo "value='$quadrant' selected"; ?>>NE</option>
				<option <?php if($quadrant == "SE") echo "value='$quadrant' selected"; ?>>SE</option>
				<option <?php if($quadrant == "SW") echo "value='$quadrant' selected"; ?>>SW</option>
				<option <?php if($quadrant == "NW") echo "value='$quadrant' selected"; ?>>NW</option>
			</select>
			
			<br>
			
			<span class="label col1">Location</span>
			<input type="text" name="location"  style="width:28em" <?php echo $abled; ?> value="<?php echo $location; ?>" />  
			<br>
			<span class="label col1">Location Notes</span>
			<textarea name="locationNotes"  style="width:28em;height:8em" <?php echo $abled; ?> ><?php echo $locationNotes; ?></textarea>
			<br>
			<span class="label col1">Group Notes</span>
			<textarea name="groupNotes"   style="width:28em;height:8em" <?php echo $abled; ?> ><?php echo $groupNotes; ?></textarea>
			<br>
			<span class="label col1"><b>Codes</b></span>
			<select name="codesPostUserEdits[]" class="required" style="float:left;" multiple size=10 <?php echo $abled; ?>>
		        <option value="O" <?php if (!(array_search("O", $codesA)===FALSE)) echo "selected"; ?>> Open (O)</option>
		        <option value="C" <?php if (!(array_search("C", $codesA)===FALSE)) echo "selected"; ?>> Closed (C)</option>
				<option value="B" <?php if (!(array_search("B", $codesA)===FALSE)) echo "selected"; ?>> Beginners (B)</option>
		        <option value="S" <?php if (!(array_search("S", $codesA)===FALSE)) echo "selected"; ?>> Steps (S)</option>
		        <option value="T" <?php if (!(array_search("T", $codesA)===FALSE)) echo "selected"; ?>> Traditions (T)</option>
		        <option value="BB" <?php if (!(array_search("BB", $codesA)===FALSE)) echo "selected"; ?>> Big Book (BB)</option>
		        <option value="D" <?php if (!(array_search("D", $codesA)===FALSE)) echo "selected"; ?>> Discussion (D)</option>
		        <option value="OD" <?php if (!(array_search("OD", $codesA)===FALSE)) echo "selected"; ?>> Open Discussion (OD)</option>
		        <option value="CD" <?php if (!(array_search("CD", $codesA)===FALSE)) echo "selected"; ?>> Closed Discussion (CD)</option>
		        <option value="OS" <?php if (!(array_search("OS", $codesA)===FALSE)) echo "selected"; ?>> Open Speaker (OS)</option>
		        <option value="YP" <?php if (!(array_search("YP", $codesA)===FALSE)) echo "selected"; ?>> Young People (YP)</option>
		        <option value="G" <?php if (!(array_search("G", $codesA)===FALSE)) echo "selected"; ?>> Gay / All Welcome (G)</option>
		        <option value="HA" <?php if (!(array_search("HA", $codesA)===FALSE)) echo "selected"; ?>> Handicap Accessible (HA)</option>
		        <option value="M" <?php if (!(array_search("M", $codesA)===FALSE)) echo "selected"; ?>> Men's Meeting (M)</option>
		        <option value="W" <?php if (!(array_search("W", $codesA)===FALSE)) echo "selected"; ?>> Women's Meeting (W)</option>
		        <option value="DF" <?php if (!(array_search("DF", $codesA)===FALSE)) echo "selected"; ?>> Sign Language Interpreted (DF)</option>
		        <option value="CP" <?php if (!(array_search("CP", $codesA)===FALSE)) echo "selected"; ?>> Couples (CP)</option>
		        <option value="LM" <?php if (!(array_search("LM", $codesA)===FALSE)) echo "selected"; ?>> Lunch Meeting (LM)</option>
		        <option value="SP" <?php if (!(array_search("SP", $codesA)===FALSE)) echo "selected"; ?>> Spanish (SP)</option>
		        <option value="GV" <?php if (!(array_search("GV", $codesA)===FALSE)) echo "selected"; ?>> Grapevine (GV)</option>
		        <option value="A" <?php if (!(array_search("A", $codesA)===FALSE)) echo "selected"; ?>> Al-Anon (A)</option>
		        <option value="RU" <?php if (!(array_search("RU", $codesA)===FALSE)) echo "selected"; ?>> Russian (RU)</option>
			</select>
			<span class="ctlNote">(Hold CTRL key while clicking to add or remove codes)</span>
			<br>
			<br>
			<div class="submitBlock">
				<?php if ($_SESSION['uiState'] == "CHANGE_DEL") { ?>
					<input type="submit" value="Save Changes" name="submit">
					<input type="submit" value="Delete Meeting" name="submit">
					<a class="label" href="index.php">Cancel</a>
				<?php } else if ($_SESSION['uiState'] == "ADD") { ?>
					<input type="submit" value="Add Meeting" name="submit">
					<a class="label" href="index.php">Cancel</a>
				<?php } else { ?>
					<a class="label" href="index.php" style='color: blue;'>Continue</a>
				<?php } ?>
			</div>
		</div>
			
	
	</form>

</div>


<?php 
include('../template/admin-footer.php'); 
?>

<?php
//---------------
Function standardizeMeeting()
{
	global	$location;
	global	$groupName;
	global	$address1;
	global	$address2;
	global	$locationNotes;
	global	$city;
	global	$zip;
	global	$quadrant;
	global	$day;
	global	$time;
	global	$time_hm;
	global	$time_meridian;
	global	$codes;
	global	$groupNotes;
	global	$focus_zip;
	global	$focus_time_hm;

	
	$errors = "";

	$location = strtoupper(trim($location));	
	
	$groupName = strtoupper(trim($groupName));
	if ($groupName == "") $errors .= "<li>Please enter a <i>Group Name</i>.";
	
	$address1 = strtoupper(trim($address1));
	if ($address1 == "") $errors .= "<li>Please complete <i>Address1</i>.";

	$address2 = strtoupper(trim($address2));
	
	$locationNotes = strtoupper(trim($locationNotes));
	
	$city = strtoupper(trim($city));
	if ($city == "") $errors .= "<li>Please enter a <i>City</i>.";
	
	if ($zip == "") $errors .= "<li>Please enter a <i>Zip</i>.";
	/*
	$nzip = intval($zip);
	$zip = strval($nzip);

	if ( !(1 <= $nzip && $nzip <= 99999))
	*/
	if (!preg_match('/^\d\d\d\d\d$/', $zip)) 
	{
		$errors .= "<li>Please correct <i>Zip</i> value.";
		$focus_zip = "autofocus";
	}
	
	$quadrant = strtoupper(trim($quadrant));
	if ( !($quadrant == ""
			|| $quadrant == "NE"
			|| $quadrant == "SE"
			|| $quadrant == "SW"
			|| $quadrant == "NW")) $errors .= "<li><i>Quadrant</i> must be NE, SE, SW, NW or blank.";
	
	$day = strtoupper(trim($day));
	if ( !($day == "SUNDAY"
			|| $day == "MONDAY"
			|| $day == "TUESDAY"
			|| $day == "WEDNESDAY"
			|| $day == "THURSDAY"
			|| $day == "FRIDAY"
			|| $day == "SATURDAY")) $errors .= "<li>Please select a <i>Day</i>.";
			
	$time_hm = strtoupper(trim($time_hm));
	$time_hm = preg_replace('/\s\s+/', ' ', $time_hm); 						// remove embedded whitespace
	if (preg_match('/^([1-9]|(10|11|12))$/', $time_hm)) $time_hm .= ":00";	// supply ":00" if lacking minutes
	if (!preg_match('/^([1-9]|(10|11|12)):[0-5][0-9]$/', $time_hm))
	{
		$errors .= "<li>Please correct <i>Time</i>; it must be in the form 'h:mm' ('h' may be 1-9, 10, 11, or 12).";
		if ($focus_zip == "") $focus_time_hm = "autofocus";
	}
	else
	{
		$time = $time_hm . " " . $time_meridian;
	}
	
	$codes = strtoupper(trim($codes));
	$codes = preg_replace('/\s+/', '', $codes);			// remove embedded whitespace
	if ($codes == "")
	{
		$errors .= "<li>Please select one or more <i>Codes</i>.";
	}
	else
	{		
		$codesArray = array_unique(explode(",", $codes));

		for ($i = 0; $i < count($codesArray); ++$i)
		{
			// Map obsolete codes to current ones
			if ($codesArray[$i] == "MO") $codesArray[$i] = "M";
			if ($codesArray[$i] == "WO") $codesArray[$i] = "W";
			if ($codesArray[$i] == "WM") $codesArray[$i] = "W";
			
			if (!validMeetingCode($codesArray[$i])) $errors .= "<li> '$codesArray[$i]' is not valid in <i>Codes</i>.";
		}
		$codes = implode(",", $codesArray);
	}
	
	$groupNotes = strtoupper(trim($groupNotes));
	
	return $errors;
}

//---------------
Function validMeetingCode($code)
{
	$validCodes = array(					// values must be unique strings (note 'flip')
		"O"		=>	"Open",
		"C"		=>	"Closed",
		"B"		=>	"Beginners",
		"S"		=>	"Steps",
		"T"		=>	"Traditions",
		"BB"	=>	"Big Book",
		"D"		=>	"Discussion",
		"OD"	=>	"Open Discussion",
		"CD"	=>	"Closed Discussion",
		"OS"	=>	"Open Speaker",
		"YP"	=>	"Young People",
		"G"		=>	"Gay / All Welcome",
		"HA"	=>	"Handicapped Accessible",	// not currently in table definition of set values
		"M"		=>	"Men's Meeting",			// not currently in table definition of set values
//		"MO"	=>	"Men-Only Meeting",			// removed - no longer an approved code
		"W"		=>	"Women's Meeting",
//		"WO"	=>	"Women-Only Meeting",		// removed - no longer an approved code
//		"WM"	=>	"Women / All Welcome",		// removed - no longer an approved code
		"DF"	=>	"Sign Language Interpreted",
		"CP"	=>	"Couples",
		"LM"	=>	"Lunch Meeting",
		"SP"	=>	"Spanish",
		"GV"	=>	"Grapevine",
		"A"		=>	"Al-Anon",
		"RU"	=>	"Russian");

	return in_array($code, array_flip($validCodes));
}



?>
